<!--登录页面-->
<template>
  <div class="login">
    <el-form class="form" :model="model" :rules="rules" ref="loginForm">
      <h1 class="title">时品卓享后台管理系统</h1>
      <el-form-item prop="userName">
        <el-input
          class="text"
          v-model="model.userName"
          prefix-icon="User"
          clearable
          :placeholder="$t('login.username')"
        />
      </el-form-item>
      <!--:placeholder="$t('login.password')"
          国际化占位符文本
          通过 Vue I18n 的 $t 函数获取翻译值
          // @/il8n/zh-cn/login.js中查看具体含义
      -->
      <el-form-item prop="password">
        <el-input
          class="text"
          v-model="model.password"
          prefix-icon="Lock"
          show-password
          clearable
          :placeholder="$t('login.password')"
        />
      </el-form-item>
      <!--验证码-->
      <el-form-item prop="captcha">
        <div class="captcha">
          <el-input
            class="text"
            v-model="model.captcha"
            prefix-icon="Picture"
            placeholder="请输入验证码"
          ></el-input>
          <img :src="captchaSrc" @click="refreshCaptcha" />
        </div>
      </el-form-item>

      <el-form-item>
        <el-button
          :loading="loading"
          type="primary"
          class="btn"
          size="large"
          @click="submit"
        >
          {{ btnText }}
        </el-button>
      </el-form-item>
    </el-form>
    <div class="change-lang">
      <change-lang />
    </div>
  </div>
</template>

<script>
import {
  defineComponent,
  getCurrentInstance,
  reactive,
  toRefs,
  ref,
  computed,
  onMounted,
  watch,
} from 'vue'
import { Login, GetValidateCode } from '@/api/login'
import { useRouter, useRoute } from 'vue-router'
import ChangeLang from '@/layout/components/Topbar/ChangeLang.vue'
import useLang from '@/i18n/useLang'
import { useApp } from '@/pinia/modules/app'
import { ElMessage } from 'element-plus'

export default defineComponent({
  components: { ChangeLang },
  name: 'login',
  setup() {
    const { proxy: ctx } = getCurrentInstance() // 可以把ctx当成vue2中的this
    const router = useRouter()
    const route = useRoute()
    const { lang } = useLang()
    // 监听语言变化，更新规则
    watch(lang, () => {
      state.rules = getRules()
    })
    //password的自定义校验规则,方便正则校验的使用
    const validatorPassword = (rule, value, callback) => {
      if (value.length >= 6 && value.length <= 12) {
        callback() //符合条件直接放行
      } else {
        callback(new Error(ctx.$t('login.rules-regpassword')))
      }
    }
    const validatorCaptcha = (rule, value, callback) => {
      if (value.length === 4) {
        callback()
      } else {
        callback(new Error('验证码必须4位！！！'))
      }
    }
    //配置输入时的规则，并且可以更换国际化语言
    const getRules = () => ({
      userName: [
        {
          required: true,
          message: ctx.$t('login.rules-username'),
          trigger: 'blur',
        },
      ],
      password: [
        {
          required: true,
          message: ctx.$t('login.rules-password'),
          trigger: 'blur',
        },
        // {  min: 6, max: 12, message: ctx.$t('login.rules-regpassword'), trigger: 'blur',},
        { trigger: 'blur', validator: validatorPassword }, //自定义校验规则
      ],
      captcha: [
        {
          required: true,
          message: ctx.$t('login.rules-validate-code'),
          trigger: 'blur',
        },
        { trigger: 'blur', validator: validatorCaptcha },
      ],
    })

    // onMounted钩子函数
    //向后端请求验证码
    onMounted(() => {
      state.refreshCaptcha()
    })

    const state = reactive({
      //绑定用户信息
      model: {
        userName: 'admin',
        password: '111111',
        captcha: '', // 用户输入的验证码
        codeKey: '', // 后端返回的验证码key
      },
      rules: getRules(), //用户信息格式校验
      loading: false, //定义变量控制按钮加载效果
      captchaSrc: '',
      refreshCaptcha: async () => {
        const { data } = await GetValidateCode()
        state.model.codeKey = data.codeKey
        state.captchaSrc = data.codeValue
      },
      btnText: computed(() =>
        state.loading ? ctx.$t('login.logining') : ctx.$t('login.login')
      ),
      loginForm: ref(null),
      //表单提交流程
      submit: () => {
        if (state.loading) {
          return
        }
        state.loginForm.validate(async valid => {
          if (valid) {
            state.loading = true
            const { code, data, message } = await Login(state.model)
            // console.log(code)
            //+code 将 code 转换为数字类型（等价于 Number(code)
            if (+code === 200) {
              //ctx.$t('login.loginsuccess')：
              // 通过国际化工具（如 Vue I18n）获取翻译后的文本
              // login.loginsuccess 是翻译键，对应实际文案（如 "登录成功"）
              ctx.$message.success({
                message: ctx.$t('login.loginsuccess'),
                duration: 1000,
              })
              // 解码重定向路径,放回退出时的那个界面
              const targetPath = decodeURIComponent(route.query.redirect)
              if (targetPath.startsWith('http')) {
                // 如果是一个url地址
                window.location.href = targetPath
              } else if (targetPath.startsWith('/')) {
                // 如果是内部路由地址
                router.push(targetPath)
              } else {
                router.push('/') // 请求成功以后，进入到首页
              }
              useApp().initToken(data) //本地存储token
            } else {
              if (code == 202) {
                console.log('验证码错误')
                ElMessage({ type: 'error', message: '验证码错误' })
              } else {
                ctx.$message.error(message)
              }
            }
            state.loading = false
          }
        })
      },
    })

    return {
      ...toRefs(state),
    }
  },
})
</script>

<style lang="scss" scoped>
.login {
  transition: transform 1s;
  transform: scale(1);
  width: 100%;
  height: 100%;
  overflow: hidden;
  // background: #2d3a4b;
  background: #2c3d53;
  .form {
    width: 520px;
    max-width: 100%;
    padding: 0 24px;
    box-sizing: border-box;
    margin: 160px auto 0;
    :deep {
      .el-input__wrapper {
        box-shadow: 0 0 0 1px rgba(255, 255, 255, 0.1) inset;
        background: rgba(0, 0, 0, 0.1);
      }
      .el-input-group--append > .el-input__wrapper {
        border-top-right-radius: 0;
        border-bottom-right-radius: 0;
      }
      .el-input-group--prepend > .el-input__wrapper {
        border-top-left-radius: 0;
        border-bottom-left-radius: 0;
      }
    }
    .title {
      color: skyblue;
      text-align: center;
      font-size: 24px;
      margin: 0 0 24px;
    }
    .text {
      font-size: 16px;
      :deep(.el-input__inner) {
        color: #fff;
        height: 48px;
        line-height: 48px;
        &::placeholder {
          color: rgba(255, 255, 255, 0.2);
        }
      }
    }
    .btn {
      width: 100%;
    }
  }
}

.captcha {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 10px;
}

.captcha img {
  cursor: pointer;
  margin-left: 20px;
}

.change-lang {
  position: fixed;
  right: 20px;
  top: 20px;
  :deep {
    .change-lang {
      height: 24px;
      // display: flex;
      // align-items: center;
      // height: 28px; // 略微增加高度提升可用性
      // padding: 0 10px;
      // border-radius: 14px;
      // background-color: rgba(0, 0, 0, 0.7);
      // backdrop-filter: blur(8px);
      // color: #fff;
      // cursor: pointer;
      // box-shadow: 0 2px 8px rgba(0, 0, 0, 0.15);
      &:hover {
        background: none;
        // background-color: rgba(0, 0, 0, 0.8);
      }
      .icon {
        color: #fff;
        // margin-right: 6px;
        // font-size: 16px;
      }
    }
  }
}
</style>